﻿using System;
using System.Text.RegularExpressions;

namespace WpfApp.Update
{

    /// <summary>
    /// 版本比较结果
    /// </summary>
    public enum VersionComparisonResult
    {
        /// <summary>
        /// 当前版本高于目标版本
        /// </summary>
        CurrentIsNewer = -1,

        /// <summary>
        /// 版本相同
        /// </summary>
        SameVersion = 0,

        /// <summary>
        /// 当前版本低于目标版本（需要更新）
        /// </summary>
        UpdateRequired = 1
    }

    public static class VersionComparer
    {
        private static readonly Regex VersionRegex = new Regex(
            @"^v?(\d+)\.(\d+)\.(\d+)(?:-.+)?$",
            RegexOptions.Compiled | RegexOptions.IgnoreCase
        );

        /// <summary>
        /// 比较两个版本号
        /// </summary>
        /// <param name="currentVersion">当前版本号（格式：x.y.z）</param>
        /// <param name="targetVersion">目标版本号（格式：x.y.z）</param>
        /// <returns>版本比较结果</returns>
        public static VersionComparisonResult Compare(string currentVersion, string targetVersion)
        {
            if (string.IsNullOrWhiteSpace(currentVersion) || string.IsNullOrWhiteSpace(targetVersion))
            {
                throw new ArgumentException("版本号不能为空或空白字符串");
            }

            var current = ParseVersion(currentVersion);
            var target = ParseVersion(targetVersion);

            return (target.Major, target.Minor, target.Patch) switch
            {
                var (maj, min, pat) when maj > current.Major => VersionComparisonResult.UpdateRequired,
                var (maj, min, pat) when maj < current.Major => VersionComparisonResult.CurrentIsNewer,
                var (maj, min, pat) when min > current.Minor => VersionComparisonResult.UpdateRequired,
                var (maj, min, pat) when min < current.Minor => VersionComparisonResult.CurrentIsNewer,
                var (maj, min, pat) when pat > current.Patch => VersionComparisonResult.UpdateRequired,
                var (maj, min, pat) when pat < current.Patch => VersionComparisonResult.CurrentIsNewer,
                _ => VersionComparisonResult.SameVersion
            };
        }

        /// <summary>
        /// 检查是否需要更新
        /// </summary>
        /// <param name="currentVersion">当前版本号</param>
        /// <param name="newVersion">新版本号</param>
        /// <returns>如果需要更新返回true，否则返回false</returns>
        public static bool IsUpdateRequired(string currentVersion, string newVersion)
        {
            return Compare(currentVersion, newVersion) == VersionComparisonResult.UpdateRequired;
        }

        private static (int Major, int Minor, int Patch) ParseVersion(string version)
        {
            var match = VersionRegex.Match(version.Trim());
            if (!match.Success)
            {
                throw new FormatException($"无效的版本号格式: {version} (应为 x.y.z 或 vx.y.z 格式)");
            }

            try
            {
                return (
                    Major: int.Parse(match.Groups[1].Value),
                    Minor: int.Parse(match.Groups[2].Value),
                    Patch: int.Parse(match.Groups[3].Value)
                );
            }
            catch (Exception ex) when (ex is FormatException || ex is OverflowException)
            {
                throw new FormatException($"版本号必须为有效数字: {version}", ex);
            }
        }
    }
}